package com.demo.flavor.widget

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

class UIProgressBar : View {

    constructor(context: Context) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        setLayerType(LAYER_TYPE_SOFTWARE, null)
    }

    var to = 20.dp2px(context)
    set(value) {
        field = value * 2
        invalidate()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        val strokeWidth = 10.dp2px(context).toFloat()
        val y = 50f + strokeWidth / 2f

        val paint = Paint()
        paint.strokeCap = Paint.Cap.ROUND
        paint.strokeWidth = strokeWidth
        paint.isAntiAlias = true
        paint.color = Color.RED

        val startX = 20.dp2px(context).toFloat()
        val width = 200.dp2px(context).toFloat() + strokeWidth

        val tracePaint = Paint()
        tracePaint.isAntiAlias = true
        tracePaint.strokeCap = Paint.Cap.ROUND
        tracePaint.strokeWidth = strokeWidth
        tracePaint.isAntiAlias = true
        tracePaint.isDither = true
        canvas?.let {
            it.drawLine(startX, y, width, y, paint)
            val left = startX - strokeWidth / 2f - 0.5f
            var top = y - strokeWidth / 2f
            if (to < strokeWidth) {
                tracePaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
                tracePaint.color = Color.RED
                it.drawLine(startX, y, startX + 5f, y, tracePaint)
                tracePaint.color = Color.YELLOW
                it.drawOval(RectF(left, top, left + to, strokeWidth + top), tracePaint)
            } else {
                tracePaint.xfermode = null
                tracePaint.color = Color.YELLOW
                it.drawLine(startX, y, startX + to.toFloat() - strokeWidth, y, tracePaint)
            }
        }
    }


}

fun Int.dp2px(ctx: Context) : Int = ctx.resources.displayMetrics.density.let { this * it + 0.5 }.toInt()